import { Component, OnInit, Input } from '@angular/core';
import { Hero } from "../hero";
import { HeroService } from "../hero.service";
import { ActivatedRoute, ParamMap } from "@angular/router";
import { Location }                 from '@angular/common';
import 'rxjs/add/operator/switchMap';

@Component({
  selector: 'hero-detail',
  // templateUrl: './hero-detail.component.html',
  template:`
<div *ngIf="hero">
  <h2>{{hero.name}} details!</h2>
  <div>
    <label>id: </label>{{hero.id}}</div>
  <div>
    <label>name: </label>
    <input [(ngModel)]="hero.name" placeholder="name" />
  </div>
  <button (click)="goBack()">Back</button>
  <button (click)="save()">Save</button>
</div>
  `,
  styleUrls: ['./hero-detail.component.css']
})
export class HeroDetailComponent implements OnInit {

  constructor(
    private heroService: HeroService,
    private route: ActivatedRoute,
    private location: Location
  ) { }
  @Input() hero:Hero;

  ngOnInit() : void {
  this.route.params.subscribe(data =>{
    this.hero = this.heroService.getHero2(+data['id'])
  } );

    // let id:number = this.route.snapshot.params["id"];
    // this.hero = this.heroService.getHero2(+id)
    
  }
  goBack(): void {
    this.location.back();
  }
  save(): void {
    this.heroService.update(this.hero)
    .subscribe(() => this.goBack());
}
}
